const router = require('koa-router')()
const dayjs = require('dayjs')
const utils = require('../utils/utils')
const uuid = require('node-uuid')
const { DATE, PLANTYPE } = require('../utils/const')

const {
  dayplanSchema,
  weekplanSchema,
  monthplanSchema,
  quarterObjectiveSchema,
  yearObjectiveSchema
} = require('../model/plans')
router.prefix('/plans')
// 获取今日任务列表
const getTodayTask = async (userId, deptId) => {
  const today = dayjs().format('YYYY-MM-DD')
  return await dayplanSchema.find({
    createTime: { $regex: today },
    userId: parseInt(userId),
    deptId: parseInt(deptId)
  })
}
//  获取昨天任务列表
const getYesterdayTask = async (userId, deptId) => {
  const today = dayjs().format('YYYY-MM-DD')
  const yesterday = utils.getYesterday(today)
  return await dayplanSchema.find({
    createTime: { $regex: yesterday },
    userId: parseInt(userId),
    deptId: parseInt(deptId)
  })
}
// 获取本周任务列表
const getCurrentWeekPlan = async (userId, deptId) => {
  const weekplan = await weekplanSchema.find({
    userId: parseInt(userId),
    deptId: parseInt(deptId)
  })
  const monday = utils.getMonday()
  return weekplan.filter((item) => {
    return new Date(item.startTime).getTime() >= new Date(monday).getTime()
  })
}
// 查找本月所有的计划-不包含今天的
const getCurrentMonthPlan = async (userId, deptId) => {
  const today = dayjs().format('YYYY-MM-DD')
  const monthFirstday = utils.getMonthFirstday()
  const monthPlans = await dayplanSchema.find({
    createTime: {
      $not: {
        $regex: today
      }
    },
    userId: parseInt(userId),
    deptId: parseInt(deptId)
  })

  const currentMonthOverdue = await monthPlans.map((item) => {
    return item.tasks.filter((task) => {
      return (
        new Date(item.createTime).getTime() >= new Date(monthFirstday).getTime()
      )
    })
  })
  // 本月计划
  const monthPlansCoverToday = await dayplanSchema.find({
    userId: parseInt(userId),
    deptId: parseInt(deptId)
  })
  const currentMonthOverdueCoverToday = await monthPlansCoverToday.map(
    (item) => {
      return item.tasks.filter((task) => {
        return (
          new Date(item.createTime).getTime() >=
          new Date(monthFirstday).getTime()
        )
      })
    }
  )
  return { currentMonthOverdue, currentMonthOverdueCoverToday, monthPlans }
}
// 获取所有任务列表
router.get('/list', async (ctx) => {
  try {
    const { userId, deptId } = ctx.request.query
    // 查找今日计划
    const dayplan = await getTodayTask(userId, deptId)
    if (dayplan.length > 0) {
      dayplan[0].tasks = dayplan[0].tasks.filter((item) => {
        return item.isFinish === false && item.state < 1 && item.state !== '100'
      })
    }
    // 查找昨天未完成计划
    const yesterdayplan = await getYesterdayTask(userId, deptId)
    if (yesterdayplan.length > 0) {
      yesterdayplan[0].tasks = yesterdayplan[0].tasks.filter((item) => {
        return item.isFinish === false && item.state < 2 && item.state !== '100'
      })
    }

    // 查找本周计划
    const currentWeek = await getCurrentWeekPlan(userId, deptId)
    if (currentWeek.length > 0) {
      currentWeek[0].tasks = currentWeek[0].tasks.filter((item) => {
        return item.isFinish === false && item.state < 1 && item.plan !== '100'
      })
    }
    // 查找本月计划
    const monthplan = await monthplanSchema.find({
      userId: parseInt(userId),
      deptId: parseInt(deptId)
    })
    const monthFirstday = utils.getMonthFirstday()
    const currentMonth = monthplan.filter((item) => {
      return (
        new Date(item.startTime).getTime() >= new Date(monthFirstday).getTime()
      )
    })
    // 查找月所有的逾期计划
    const { currentMonthOverdue, currentMonthOverdueCoverToday } =
      await getCurrentMonthPlan(userId, deptId)
    const currentMonthOverdues = currentMonthOverdue.map((item) => {
      return item.filter((task) => {
        return task.isFinish === false && task.state < 1 && task.plan < 100
      })
    })

    // 本月延期计划postpone
    const currentMonthPostpone = currentMonthOverdueCoverToday.map((item) => {
      return item.filter((task) => {
        return task.isFinish === false && task.state === 1 && task.plan < 100
      })
    })
    // 季度目标
    const quarterObjective = await quarterObjectiveSchema.find({
      userId: parseInt(userId),
      deptId: parseInt(deptId)
    })
    // 年度目标
    const yearObjective = await yearObjectiveSchema.find({
      userId: parseInt(userId),
      deptId: parseInt(deptId)
    })

    ctx.body = utils.success({
      dayplan,
      yesterdayplan,
      overdueplan: currentMonthOverdues,
      weekplan: currentWeek,
      monthplan: currentMonth,
      currentMonthPostpone,
      quarterObjective,
      yearObjective
    })
  } catch (error) {
    ctx.body = utils.fail(error.msg)
  }
})
// 添加任务
router.post('/addTask', async (ctx) => {
  const { userId, taskName, type, number, taskDesc, planType, deptId } =
    ctx.request.body
  const today = dayjs().format('YYYY-MM-DD')
  const monday = utils.getMonday()
  try {
    const task = {
      taskId: uuid.v4(),
      taskName,
      type,
      number,
      state: 0,
      plan: 0,
      isFinish: false,
      taskDesc,
      finishTime: '',
      noFinishDesc: ''
    }
    const tasks = []

    // 添加今日任务
    if (planType === PLANTYPE.today) {
      const hasData = await getTodayTask(userId, deptId).then((res) => {
        return res
      })
      if (hasData.length > 0) {
        // 往今天添加任务
        const upRes = await dayplanSchema.updateOne(
          {
            createTime: today
          },
          {
            tasks: [...hasData[0].tasks, task]
          }
        )
        if (upRes.modifiedCount === 1 && upRes.matchedCount === 1) {
          // 更新成功
          ctx.body = utils.success({}, '任务添加成功')
        } else {
          // 更新失败
          ctx.body = utils.fail('任务添加失败')
        }
      } else {
        // 新增今天数据
        tasks.push(task)
        // eslint-disable-next-line new-cap
        const dayplay = await new dayplanSchema({
          userId,
          createTime: today,
          deptId,
          tasks,
          question: ''
        })
        await dayplay.save((err, data) => {
          if (err) {
            ctx.body = utils.fail(err.msg)
            return false
          }
        })
        ctx.body = utils.success({}, '添加成功')
      }
    }
    // 添加本周任务
    if (planType === PLANTYPE.week) {
      const currentWeek = await getCurrentWeekPlan(userId, deptId)
      // 已有本周数据，新增
      if (currentWeek.length > 0) {
        // 往今天添加任务
        const upRes = await weekplanSchema.updateOne(
          {
            startTime: monday
          },
          {
            tasks: [...currentWeek[0].tasks, task]
          }
        )
        if (upRes.modifiedCount === 1 && upRes.matchedCount === 1) {
          // 更新成功
          ctx.body = utils.success({}, '任务添加成功')
        } else {
          // 更新失败
          ctx.body = utils.fail('任务添加失败')
        }
      } else {
        // 没有本周数据创建

        tasks.push(task)
        // eslint-disable-next-line new-cap
        const weekplay = await new weekplanSchema({
          userId,
          createTime: monday,
          startTime: monday,
          deptId,
          tasks,
          question: ''
        })
        await weekplay.save((err, data) => {
          if (err) {
            ctx.body = utils.fail(err.msg)
            return false
          }
        })
        ctx.body = utils.success({}, '添加成功')
      }
    }
  } catch (error) {
    ctx.body = utils.fail(error.msg)
  }
})
// 修改任务
router.post('/editTask', async (ctx) => {
  const {
    taskId,
    userId,
    deptId,
    taskName,
    plan,
    type,
    number,
    state,
    taskDesc,
    whichDay,
    planType,
    isFinish,
    noFinishDesc
  } = ctx.request.body
  try {
    const today = dayjs().format('YYYY-MM-DD')

    let findWhichDay = ''
    const yesterday = utils.getYesterday(today)
    const monday = utils.getMonday()

    let hasData = null
    if (whichDay === DATE.today) {
      // 查询今天
      findWhichDay = today
      hasData = await getTodayTask(userId, deptId).then((res) => {
        return res
      })
    } else if (whichDay === DATE.yesterday) {
      findWhichDay = yesterday
      hasData = await getYesterdayTask(userId, deptId).then((res) => {
        return res
      })
    } else if (whichDay === DATE.currentMonthDay) {
      // 先查出本月所有的计划
      const { monthPlans } = await getCurrentMonthPlan(userId, deptId)
      const monthFirstday = utils.getMonthFirstday()

      const currentMonth = monthPlans.filter((item) => {
        return (
          new Date(item.createTime).getTime() >=
          new Date(monthFirstday).getTime()
        )
      })

      // 根据id匹配出任务
      const res = []
      currentMonth.forEach((item) => {
        item.tasks.forEach((task) => {
          if (task.taskId === taskId) {
            res.push(item)
            findWhichDay = item.createTime
            hasData = res
          }
        })
      })
    }
    if (planType === PLANTYPE.week) {
      // 更新周任务
      hasData = await getCurrentWeekPlan(userId, deptId)
    }
    const task = {
      taskId,
      taskName,
      type,
      number,
      plan,
      isFinish,
      state,
      taskDesc,
      finishTime: '',
      noFinishDesc
    }

    for (let i = 0; i < hasData[0].tasks.length; i++) {
      if (hasData[0].tasks[i].taskId === taskId) {
        hasData[0].tasks[i] = task
        break
      }
    }
    let upRes = null
    if (planType === PLANTYPE.week) {
      upRes = await weekplanSchema.updateOne(
        {
          startTime: monday
        },
        {
          tasks: [...hasData[0].tasks]
        }
      )
    } else {
      upRes = await dayplanSchema.updateOne(
        {
          createTime: findWhichDay
        },
        {
          tasks: [...hasData[0].tasks]
        }
      )
    }

    if (upRes.modifiedCount === 1 && upRes.matchedCount === 1) {
      // 更新成功
      ctx.body = utils.success({}, '修改成功')
    } else {
      // 更新失败
      ctx.body = utils.fail('任务修改失败')
    }
  } catch (error) {
    ctx.body = utils.fail(error.msg)
  }
})

// 一键完成当日/本周任务
router.post('/completeTasks', async (ctx) => {
  const { userId, planType, deptId } = ctx.request.body
  let hasData = null
  let upRes = null
  const monday = utils.getMonday()
  const today = dayjs().format('YYYY-MM-DD')

  if (planType === PLANTYPE.today) {
    hasData = await getTodayTask(userId, deptId).then((res) => {
      return res
    })
    hasData[0].tasks.forEach((item) => {
      item.isFinish = true
      item.plan = 100
    })
    upRes = await dayplanSchema.updateOne(
      {
        createTime: today
      },
      {
        tasks: [...hasData[0].tasks]
      }
    )
  }
  if (planType === PLANTYPE.week) {
    hasData = await getCurrentWeekPlan(userId, deptId)
    hasData[0].tasks.forEach((item) => {
      item.isFinish = true
      item.plan = 100
    })
    upRes = await weekplanSchema.updateOne(
      {
        startTime: monday
      },
      {
        tasks: [...hasData[0].tasks]
      }
    )
  }

  if (upRes.modifiedCount === 1 && upRes.matchedCount === 1) {
    // 更新成功
    ctx.body = utils.success({}, '全部完成')
  } else {
    // 更新失败
    ctx.body = utils.fail('操作失败')
  }
})
module.exports = router
